package com.ljw.gulimall.product.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ljw.common.constant.AuthServiceConstant;
import com.ljw.common.utils.GetCookieUtils;
import com.ljw.common.utils.JwtUtils;
import com.ljw.common.vo.UserLoginWxVo;
import com.ljw.gulimall.product.entity.CategoryEntity;
import com.ljw.gulimall.product.service.CategoryService;
import com.ljw.gulimall.product.vo.Catelog2Vo;
import com.ljw.gulimall.product.vo.MemberVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model, HttpServletRequest request){

        //TODO 1、查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntities);
        String memberIdByJwtToken = GetCookieUtils.getMemberIdFormCookie(request);
        if (memberIdByJwtToken != null){
            String memberInfoJson = redisTemplate.opsForValue().get(memberIdByJwtToken);
            MemberVo memberVo = JSON.parseObject(memberInfoJson, new TypeReference<MemberVo>() {
            });
            model.addAttribute("loginUser", memberVo);
            System.out.println(memberInfoJson);
        }
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null){
//            for (Cookie cookie : cookies) {
//                if (cookie.getName().equals("GULIMASESSION")){
//                    String loginUserJSON = redisTemplate.opsForValue().get(cookie.getValue());
//                    if (loginUserJSON != null){
//                        UserLoginWxVo loginWxVo = JSON.parseObject(loginUserJSON, new TypeReference<UserLoginWxVo>() {
//                        });
//                        model.addAttribute("loginUser", loginWxVo);
//                    }
//                }
//            }
//        }
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "Hello";
    }
}
